/*
 * InterestDAO.java
 * 
 * Created on February 19, 2007, 7:09 PM
 */

package edu.byu.isys413.jjenkins.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

 /**
 * This class contains methods to create, read, update and delete the 
 * Interest Object. It also contains methods to read an object by
 * serveral different criteria. All interaction between the object 
 * and the database is done through this class. 
 * 
 * @author      Jeff Jenkins
 * @version     1.0
 * 
 */
public class InterestDAO {
    
    private static InterestDAO instance = null;
    
    /** Creates a new instance of InterestDAO */
    private InterestDAO() {
    }
    
    
    
    /* This method implements the singleton pattern. It insures that only
     * on instance of InterestDAO exists
     *
     * @return: InterestDAO instance */
    
    public static synchronized InterestDAO getInstance() {
        if (instance == null) {
            instance = new InterestDAO();
        }
        return instance;
    }
    
    
    /* This method creates a new Intrest BO with a unique QUID, puts the interest
     * in cache, and then returns it to the calling method.
     *
     * @return: InterestBO: interest
     * @throws: DataException
     */
    
    public InterestBO create() throws DataException {
        try {
            
            String id = GUID.generate();
            InterestBO interest = new InterestBO();
            interest.setId(id);
            Cache.getInstance().put(interest.getId(), interest);
            return interest;
        } catch (Exception e) {
            throw new DataException("Could not create GUID", e);
        }
        
    }
    
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     *
     * @Par: String: id
     * @Return: InterestBO
     * @Throws: DataException
     */
    public synchronized InterestBO read(String id) throws DataException {
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        InterestBO interest = (InterestBO)cache.get(id);
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // If the item is not in cache a connection is checked out and
            // The item is read from the database.
            if(interest == null){
                try {
                    //reads in customer
                    interest = read(id, conn);
                    
                }catch (SQLException e) {
                    conn.rollback();
                    throw new DataException("Could not retrieve record for id=" + id, e);
                }
            }
            
            // After all items are read (customer, membership, interest) the
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // Return Interest
        return interest;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  @Par: String: id, Connection conn
     *  @Return: InterestBO
     *  @throws: DataException, SQLException
     */
    synchronized InterestBO read(String id, Connection conn) throws SQLException, DataException {
        
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        InterestBO interest = (InterestBO)cache.get(id);
        
        // Quieries that database
        if(interest == null){
            
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM area_of_interest WHERE interest_id = ?");
            pstmt.setString(1, id);
            pstmt.execute();
            ResultSet rs = pstmt.getResultSet();
            
            if (rs.next()) {
                interest = new InterestBO();
                interest.setId(rs.getString("interest_id"));
                interest.setDescription(rs.getString("description"));
                
                
                // Sets already in database
                interest.setObjectAlreadyInDB(true);
                
                // adds to cache
                cache.put(interest.getId(), interest);
                
            }else{
                throw new DataException("Object was not found in the database.");
            }
        }
        
        
        // returns customer
        return interest;
    }
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     *
     * @par InterestBO interest
     * @throws DataExcpetion
     */
    public synchronized void save(InterestBO interest) throws DataException {
        try {
            
            
            // retrieve a database connection from the pool
            ConnectionPool connPool = ConnectionPool.getInstance();
            
            Connection conn = connPool.get();
            
            
            try {
                
                // Saves Interest
                save(interest, conn);
                
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not save record for" + interest.getId(), e);
            }
            
            // After all items are saved (customer, membership, interest) the
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            // touch the cache for the object
            Cache.getInstance().touch(interest.getId());
            
            
            
        } catch (DataException e) {
            throw new DataException("Could not save record for" + interest.getId(), e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not save record for" + interest.getId(), e);
        } catch (SQLException e) {
            throw new DataException("Could not save record for" + interest.getId(), e);
        }
        
        
    }
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     *
     *  @par: InterestBO, Connection conn
     *  @throws: SQLException, DataException
     */
    synchronized void save(InterestBO interest, Connection conn) throws SQLException, DataException {
        
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (interest.isDirty()) {
            if (interest.isObjectAlreadyInDB()) {
                update(interest, conn);
            }else{
                insert(interest, conn);
            }
            interest.setDirty(false);
        }
        
        
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @Par InterstBO interest
     */
    private synchronized void update(InterestBO interest, Connection conn) throws SQLException, DataException {
        
        PreparedStatement pstmt = conn.prepareStatement("UPDATE area_of_interest SET interest_id = ?, description = ? WHERE interest_id = ?");
        pstmt.setString(1, interest.getId());
        pstmt.setString(2, interest.getDescription());
        pstmt.setString(3, interest.getId());
        
        
        pstmt.execute();
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @Par IntersetBO interest
     */
    private synchronized void insert(InterestBO interest, Connection conn) throws SQLException, DataException {
        
        // Creates prepared statemetn
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO area_of_interest VALUES(?, ?)");
        pstmt.setString(1, interest.getId());
        pstmt.setString(2, interest.getDescription());
        
        //Executes prepated statement
        pstmt.execute();
        
        //Sets already in database true
        interest.setObjectAlreadyInDB(true);
        
    }
    
    
    /* We intentionally do not allow a interst object to be deleted because
     * it could mess up relationships in the database */
    
    public synchronized void delete(CustomerBO customer)throws DataException{
        /* We intentionally do not allow a interset object to be deleted because
         * it could mess up relationships in the database */
        throw new DataException("You can not delete a interest");
    }
    
    /* This method queries that database for a list of all interest. It puts these objecs
     * in a list
     *
     *
     * &return: list <String[]>
     */
    
    public List<InterestBO> getAll() throws DataException {
        
        // List to store the string array of customers
        List list = new LinkedList();
        
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // Creates statement and populates list
            try {
                
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM area_of_interest");
                pstmt.execute();
                ResultSet rs = pstmt.getResultSet();
                
                Cache cache = Cache.getInstance();
                
                while(rs.next()){
                    InterestBO interest = new InterestBO();
                    interest.setId(rs.getString("interest_id"));
                    interest.setDescription(rs.getString("description"));
                    list.add(interest);
                    cache.put(interest.getId(),interest);
                    
                }
                
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not retrieve list of interest " + e);
            }
            
            // After all items are read (customer, membership, interest) the
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve list of interest " + e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve list of interest " + e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve list of interest " + e);
        }
        
        // Return Interests
        return list;
        
    }
    
        /*This method queries that database for a list of all interseetwith a certain
         * description. It adds these objects to a list and puts them
         * in cache
         *
         *&return: list <of interest>
         */
    public List<InterestBO> getByName(String description) throws DataException {
        // List to store the string array of interests
        List list = new LinkedList();
        
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // Creates statement and populates list
            try {
                
                // prepares statemnt
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM area_of_interest WHERE description = ?");
                pstmt.setString(1, description);
                pstmt.execute();
                ResultSet rs = pstmt.getResultSet();
                
                //get instance of cache to put objects in
                Cache cache = Cache.getInstance();
                
                while(rs.next()){
                    
                    InterestBO interest = new InterestBO();
                    interest.setId(rs.getString("interest_id"));
                    interest.setDescription(rs.getString("description"));
                    list.add(interest);
                    cache.put(interest.getId(),interest);
                    
                    
                }
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not retrieve list of interest " + e);
            }
            
            // After all items are read (customer, membership, interest) the
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve list of interests " + e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve list of interests " + e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve list of interests " + e);
        }
        
        // Return List of Interest by Name
        return list;
    }

}
